var stage = new createjs.Stage('gameView');
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener('tick',stage);
var gameView = new createjs.Container();
stage.addChild(gameView);

//判断使用的设备是不是PC端的函数
function IsPC(){  
	var userAgentInfo = navigator.userAgent;  
	var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");  
	var flag = true;  
	for (var v = 0; v < Agents.length; v++) {  
		if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }  
	}  
	return flag;  
}  

//获取设备可视区的宽度
var cWidth = document.body.clientWidth;
var canvas = document.getElementById('gameView');
canvas.height = canvas.width = cWidth;

//判断当前设备是不是PC端，如果是就执行以下代码
if(IsPC()){
	cWidth = 400;
	canvas.height = canvas.width = cWidth;
	document.documentElement.style.fontSize = '40px';
}

//声明并初始化数据
var n = 2;
var a = 0;
var guanshu = 0;

var gsjs = document.getElementById('gsjs');

function getNum (){
	return parseInt(Math.random()*255);
}

function addRect(){
	//声明并初始化数据
	var red = getNum();
	var green = getNum();
	var blue = getNum();
	var red1;
	var green1;
	var blue1;

	//给那个不同颜色的方块取色
	if(red<17){
		red1 = parseInt(red+17);
	}else {
		red1 = parseInt(red-17);
	}
	if(green<17){
		green1 = parseInt(green+17);
	}else {
		green1 = parseInt(green-17);
	}
	if(blue<17){
		blue1 = parseInt(blue+17);
	}else {
		blue1 = parseInt(blue-17);
	}

	//给相同的方块添加颜色
	var color = 'rgb('+red+','+green+','+blue+')';
	//给唯一不同颜色的方块添加颜色
	var reacColor = 'rgb('+red1+','+green1+','+blue1+')';

	//随机设置X,Y
	var x = parseInt(Math.random()*n);
	var y = parseInt(Math.random()*n);

	for(var indexX = 0;indexX<n;indexX++){
		for( var indexY = 0;indexY<n;indexY++){
			//构造rect实例
			var r = new Rect(n,color,reacColor,cWidth);
			gameView.addChild(r);
			r.x = indexX;
			r.y = indexY;
			if(r.x == x && r.y == y){
				r.setRectType(2);
			}
			r.x = indexX*(cWidth/n);
			r.y = indexY*(cWidth/n);
			if(r.getRectType() == 2){
				r.addEventListener('click',function(){
					guanshu++;

					gsjs.innerText = guanshu;
					
					if(a<=n){
						a++;
					}else {
						++n;
						a = 0;
					}
					gameView.removeAllChildren();
					addRect();
				})
			}
		}
	}
}
//初始化画布
addRect();


/**
 * 这里是遮罩层
 */

var mask = document.getElementById('mask');
var star = document.getElementById('star');
var jsq = document.getElementById('jsq');
var textInfo = document.querySelectorAll('#mask p')[0];

var jishi = 59;
var timer;

star.addEventListener('click',function(){
	//控制遮罩层隐藏
	mask.style.display = 'none';

	//设置定时器
	timer = setInterval(function(){
		//动态编辑文本
		jsq.innerText = jishi;
		jishi--;
		//当计时为0时的判断
		if(jishi == -1){
			//清楚定时器
			clearInterval(timer);
			//控制遮罩层显示
			mask.style.display = 'block';
			jsq.innerText = 60;
			jishi = 59;
			textInfo.innerText = '本轮游戏积分为'+ gsjs.innerText + '分';

			star.innerText = '点击开始新一轮游戏';
			gsjs.innerText = 0;

			//画布初始化
			gameView.removeAllChildren();
			n = 2;
			addRect();
		}
	},1000)
})